<template>
  <div class="app-container">
    <div class="custom_card_0" v-show="showSearch">
      <el-form :model="queryParams" ref="queryForm" inline label-width="68px">
        <div style="display: flex;">
          <div :class="{ 'min-box': !showAll }">

            <el-form-item label="客户名称" prop="memberName">
              <el-input v-model="queryParams.memberName" placeholder="请输入客户名称" clearable size="small"
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="客户类型" prop="memberType">
              <el-select v-model="queryParams.memberType" placeholder="请选择客户类型" clearable size="small"
                @1change="handleQuery">
                <el-option v-for="dict in dict.type.memberType" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="客户来源" prop="memberSource">
              <el-select v-model="queryParams.memberSource" placeholder="请选择客户来源" clearable size="small"
                @1change="handleQuery">
                <el-option v-for="dict in dict.type.memberSource" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="手机号" prop="contactPhone">
              <el-input v-model="queryParams.contactPhone" placeholder="请输入手机号" clearable size="small"
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="客户状态" prop="memberStatus">
              <el-select v-model="queryParams.memberStatus" placeholder="请选择客户状态" clearable @1change="handleQuery"
                size="small">
                <el-option v-for="dict in dict.type.memberStatus" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="认证状态" prop="censorStatus">
              <el-select v-model="queryParams.censorStatus" placeholder="请选择客户状态" clearable @1change="handleQuery"
                size="small">
                <el-option v-for="dict in dict.type.censorStatus" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>

            <el-form-item label="转化渠道" prop="memberSource">
              <el-select v-model="queryParams.memberSource" placeholder="请选择客户转化渠道" clearable size="small"
                @1change="handleQuery">
                <el-option v-for="dict in dict.type.memberSource" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>

            <el-form-item label="注册时间" prop="takeStartTime">
              <el-date-picker size="small" v-model="takeTime" type="daterange" range-separator="至"
                :picker-options="{ disabledDate: data => new Date(data).getTime() > (new Date().getTime()) }"
                value-format="yyyy-MM-dd" start-placeholder="开始时间" end-placeholder="结束时间"></el-date-picker>
            </el-form-item>
          </div>

          <div style="align-self: flex-end;">
            <el-form-item style="width: 220px;!important;">
              <el-button type="primary" size="medium" icon="el-icon-search" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="medium" @click="resetQuery">重置</el-button>
              <el-button type="text" size="mini" @click="showAll = !showAll; resetQueruyForm()">{{ showAll ? '收起' : '展开'
                }}<i :class="showAll ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></el-button>
            </el-form-item>
          </div>

        </div>
      </el-form>
    </div>


    <div class="custom_card">
      <el-row :gutter="10" v-if="!onlyList" class="mb10">
        <el-col :span="1.5">
          <el-button class="first-plain-btn" size="medium" @click="handleAdd"
            v-hasPermi="['member:basic:add']">新&nbsp;&nbsp;增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button class="sec-plain-btn" size="medium" :loading="exportLoading" @click="handleExport"
            v-hasPermi="['member:basic:export']">导&nbsp;&nbsp;出
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button class="thr-plain-btn" size="medium" @click="handleImport"
            v-hasPermi="['member:basic:import']">导&nbsp;&nbsp;入
          </el-button>
        </el-col>


        <el-col :span="1.5">
          <el-button class="four-plain-btn" size="medium" @click="customerEvaluation"
            v-hasPermi="['risk:credit:index']">反欺诈
          </el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button class="five-plain-btn" size="medium" @click="conversionFunnelStatistics"
            v-hasPermi="['member:basic:funnel']">渠道转化统计
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="basicList" @selection-change="handleSelectionChange" border>

        <el-table-column label="客户名称" align="center" prop="memberName" min-width="150" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{
              scope.row.memberType == 1
                ? scope.row.enterpriseName
                : scope.row.memberName
            }}
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center" prop="contactPhone" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column label="客户类型" align="center" prop="memberType" min-width="100" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.memberType" :value="scope.row.memberType" />
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="昵称"
          align="center"
          prop="vxName"
          min-width="100"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="微信图像"
          align="center"
          min-width="100"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="{ row }">
            <el-avatar :src="row.vxUrl"></el-avatar>
          </template>
        </el-table-column> -->
        <el-table-column label="最后登陆时间" align="center" prop="lastLoginTime" min-width="160"
          :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.lastLoginTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客户来源" align="center" prop="memberSource" min-width="160" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <!--            <div style="display: flex;align-items: center">-->
            <dict-tag :options="dict.type.memberSource" :value="scope.row.memberSource" />
            <!--              <el-tag style="margin-left: 10px" type="success">中升go</el-tag>-->
            <!--            </div>-->

          </template>
        </el-table-column>
        <!-- <el-table-column
          label="联系地址"
          align="center"
          prop="contactAddress"
          min-width="150"
          :show-overflow-tooltip="true"
        /> -->
        <el-table-column label="客户状态" align="center" prop="memberStatus" min-width="100" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.memberStatus" :value="scope.row.memberStatus" />
          </template>
        </el-table-column>
        <el-table-column label="客户标签" align="center" prop="labelClassify" min-width="180" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-tag type="success" v-for="(label, index) in scope.row.labelClassify" :key="index">
              <div>
                <dict-tag :options="dict.type.label_classify" :value="label" />
              </div>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="客户认证状态" align="center" prop="censorStatus" min-width="100"
          :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.censorStatus" :value="scope.row.censorStatus" />
          </template>
        </el-table-column>

        <template v-if="electronicContractEnable == 1">
          <el-table-column label="电子合同认证状态" align="center" prop="authenticationStatus" min-width="140"
            :show-overflow-tooltip="true">
            <template v-slot="{ row }">
              {{ row.authenticationStatus | authenticationStatus }}
            </template>
          </el-table-column>

          <el-table-column label="电子合同认证结果" align="center" min-width="140">
            <template v-slot="{ row }">
              <el-button v-if="row.authenticationStatus !== 1 && row.authenticationUrl && row.authenticationUrl != ''"
                size="mini" type="text" @click="goAuthResult(row)">查看认证结果
              </el-button>
              <div v-else>--</div>
            </template>
          </el-table-column>
        </template>

        <el-table-column label="邀请人" align="center" prop="inviterName" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" align="center" prop="createTime" min-width="160" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属租户" align="center" prop="tenantName" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="操作" v-if="!onlyList" align="center" class-name="small-padding fixed-width"
          min-width="280" fixed="left">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleDetail(scope.row)">详情
            </el-button>
            <el-button size="mini" type="text" @click="handleUpdate(scope.row)" v-hasPermi="['member:basic:edit']">修改
            </el-button>
            <el-popconfirm title="您确定删除吗？" style="margin-left: 10px" @confirm="handleDelete(scope.row)">
              <el-button size="mini" type="text" slot="reference" v-hasPermi="['member:basic:remove']">删除
              </el-button>
            </el-popconfirm>

            <el-popconfirm style="margin-left: 10px" :title="`您确定${scope.row.memberStatus == 1 ? '加入' : '取消'
              }黑名单吗？`" @confirm="handleStatus(scope.row)">
              <el-button size="mini" type="text" slot="reference" v-hasPermi="['member:basic:edit']">
                {{ scope.row.memberStatus == 1 ? '加入' : '取消' }}黑名单
              </el-button>
            </el-popconfirm>


            <el-button v-if="electronicContractEnable == 1" style="margin-left: 10px" size="mini" type="text"
              @click="sendAuthentication(scope.row)">认证
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>
    <!-- 添加或修改会员基础信息对话框 -->

    <el-dialog :title="title" :visible.sync="open" width="1100px" destroy-on-close append-to-body>
      <MmvAdd ref="MmvAdd" v-if="open" :editid="editid" :electronic-contract-enable="electronicContractEnable"></MmvAdd>
      <div slot="footer" v-if="open">
        <el-button @click="open = false">取消</el-button>
        <el-button type="primary" @click="submitForms()" :loading="submitLoading">确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="详情" :visible.sync="opendetail" width="900px" destroy-on-close append-to-body
      @colse="detailid = null">
      <MmvDetail v-if="opendetail" :detailid="detailid"></MmvDetail>
    </el-dialog>


    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body class="uploadBox">
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag><i
          class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip"><span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBasic,
  importTemplate,
  delBasic,
  addBasic,
  updateBasic,
  exportBasic,
  editMemberStatus,
  memberOrderList,
} from '@/api/member/member'
import { memberCertification } from "@/api/customer/customer";
import ImageUpload from '@/components/ImageUpload/index.vue'
import MmvAdd from './add.vue'
import MmvDetail from './detail.vue'
import * as api from "@/api/order";
import { getToken } from "@/utils/auth";
import { illegalQueryPriceDetail } from "@/api/credit/credit";

export default {
  name: 'Member',
  dicts: [
    'memberType',
    'memberSource',
    'memberStatus',
    'censorStatus',
    'label_classify',
  ],
  props: ['onlyList'],
  components: {
    ImageUpload,
    MmvAdd,
    MmvDetail,
  },
  data() {
    return {
      showAll: false,
      electronicContractEnable: 0,
      submitLoading: false,
      opendetail: false,
      detailid: null,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      takeTime: [],
      selection: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会员基础信息表格数据
      basicList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        memberName: null,
        memberType: null,
        memberSource: null,
        contactPhone: null,
        memberStatus: null,
        censorStatus: null,
      },
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {
          Authorization: 'Bearer ' + getToken()
        },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/member/basic/import'
      },
      memberTypeOptions: [
        {
          label: '企业',
          value: 1,
        },
        {
          label: '个人',
          value: 2,
        },
      ],
      // 表单参数
      formData: {
        memberType: 2,
        memberName: undefined,
        contactPhone: undefined,
        contactAddress: undefined,
        cardId: undefined,
        cardValidity: null,
        field111: null,
        drivingType: undefined,
        field117: null,
        field112: null,
        remark: undefined,
        jsUrl: [], // 驾驶证图片
        sfUrl: [], // 证件图片
      },
      field111Action: 'https://jsonplaceholder.typicode.com/posts/',
      field111fileList: [],
      field112Action: 'https://jsonplaceholder.typicode.com/posts/',
      field112fileList: [],
      // 表单校验
      rules: {},

      editid: null,
    }
  },
  computed: {
    tenantId() {
      return this.$store.state.user.tenantId;
    }
  },
  created() {
    this.getTenantInfo();
    this.getList();
  },
  activated() {
    this.getList();
  },
  methods: {
    //发起认证
    sendAuthentication(row) {
      this.$alert('确定发起认证吗?', '发起认证', {
        confirmButtonText: '确定',
        callback: action => {
          if (action == 'confirm') {
            memberCertification(row.memberNo).then(res => {
              this.$message({
                type: 'success',
                message: '发起成功'
              });
              this.handleQuery();
            })
          }
        }
      });
    },
    // 查看认证结果
    goAuthResult(row) {
      window.open(row.authenticationUrl, '_blank');
      // window.open('https://www.baidu.com', '_blank');
    },
    // 获取租户是否开始电子合同
    getTenantInfo() {
      illegalQueryPriceDetail(this.tenantId).then(res => {
        this.electronicContractEnable = res.data?.electronicContractEnable || 0;
      })
    },

    /** 抛出数据 */
    emitData() {
      return this.selection[0]
    },
    onOpen() {
    },
    onClose() {
      this.$refs['memberForm'].resetFields()
    },
    close() {
      this.$emit('update:visible', false)
    },
    handelConfirm() {
      this.$refs['memberForm'].validate((valid) => {
        if (!valid) return
        this.close()
      })
    },
    field111BeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      return isRightSize
    },
    field112BeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      return isRightSize
    },
    /** 查询会员基础信息列表 */
    getList() {
      this.loading = true
      if (this.takeTime) {
        this.queryParams.createStartTime = this.parseTime(this.takeTime[0], '{y}-{m}-{d} 00:00:00')
        this.queryParams.createEndTime = this.parseTime(this.takeTime[1], '{y}-{m}-{d} 23:59:59')
      } else {
        this.queryParams.createStartTime = null
        this.queryParams.createEndTime = null
      }
      listBasic(this.queryParams).then((response) => {
        this.basicList = response.rows
        this.basicList.forEach((i) => {
          i.labelClassify = i.labelClassify.split(',')
        })
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        memberNo: null,
        memberName: null,
        memberType: null,
        vxName: null,
        vxUrl: null,
        lastLoginTime: null,
        memberSource: null,
        contactPhone: null,
        contactAddress: null,
        cardId: null,
        cardValidity: null,
        drivingType: null,
        drivingValidity: null,
        memberStatus: null,
        integral: null,
        qrCode: null,
        inviterId: null,
        inviterName: null,
        openId: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        tenantId: null,
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.takeTime = []
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection
      this.ids = selection.map((item) => item.memberNo)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.editid = null
      this.reset()
      this.open = true
      this.title = '新增客户'
    },
    customerEvaluation() {
      this.$router.push({ path: '/riskManagement/risk' });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.editid = row.memberNo
      this.open = true
      this.title = '修改会员基础信息'
    },
    /** 提交按钮 */
    submitForms() {
      try {
        this.$refs['MmvAdd'].validate().then((valid) => {
          if (valid) {
            this.submitLoading = true
            const form = this.$refs['MmvAdd'].emitData()
            if (form.memberNo != null) {
              updateBasic(form).then((response) => {
                this.$modal.msgSuccess('修改成功')
                this.open = false
                this.getList()
                this.submitLoading = false
              })
            } else {
              addBasic(form).then((response) => {
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.getList()
                this.submitLoading = false
              })
            }
          }
        })
      } catch (error) {
        this.submitLoading = false
        this.$message.error(error.message)
      }

      setTimeout(() => {
        this.submitLoading = false
      }, 2e3)
    },
    handleDetail(row) {
      this.$router.push({
        name: 'member_detail',
        query: { memberNo: row.memberNo, electronicContractEnable: this.electronicContractEnable },
      })
    },
    /** 黑名单状态处理 */
    handleStatus(row) {
      editMemberStatus({
        memberStatus: row.memberStatus == 1 ? 2 : 1, // 取消（拉入）黑名单（1.取消黑名单 2.拉入黑名单）
        memberNo: row.memberNo, // 	客户编号
      }).then((res) => {
        this.getList()
        this.$modal.msgSuccess('操作成功')
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const memberNos = row.memberNo || this.ids
      this.$modal
        .confirm('是否确认删除会员基础信息？')
        .then(function () {
          return delBasic(memberNos)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$modal
        .confirm('是否确认导出所有会员基础信息数据项？')
        .then(() => {
          this.exportLoading = true
          return exportBasic(queryParams)
        })
        .then((response) => {
          this.$download.name(response.msg)
          this.exportLoading = false
        })
        .catch(() => {
        })
    },
    // 渠道转化统计
    conversionFunnelStatistics() {
      this.$router.push({
        name: 'member_channelStatistics',

      })
    },
    // 删除门店图片
    storeImageRemove(file) {
      this.formData.storeImage = null
    },
    // 上传成功门店回调
    storeImageSuccess(res) {
      this.formData.storeImage = res.fileName
      this.$refs['form'].validateField('storeImage')
      console.log(this.formData)
    },


    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '客户导入'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        this.$download.name(response.msg)
      })
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.msg, '导入结果', {
        dangerouslyUseHTMLString: true
      })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
  },
}
</script>
<style scoped lang="scss">
.el-form-item {
  margin-bottom: 10px;
}

.min-box {
  overflow: hidden;
  height: 40px
}
</style>
